﻿using blackhouse.Translator.Business;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace blackhouse.Translator.Web {
    public partial class TranslatorModule : System.Web.UI.UserControl {

        #region Fields

        private TranslatorResourcesManager resourcesManager;
        private WebTranslatorLanguagesManager languagesManager;

        private ITranslatorResource[] allResources;
        private ITranslatorResource selectedResource;

        private CultureInfo[] languages;
        private CultureInfo fromLanguage;
        private CultureInfo toLanguage;

        private string[] resourceKeys;

        #endregion

        #region Page Cycle

        protected override void OnInit(EventArgs e) {
            base.OnInit(e);

            this.lnkChangeParameters.Click += this.lnkChangeParameters_Click;
            this.lnkSave.Click += this.lnkSave_Click;
            this.SetScenario();
        }

        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);

            if (!this.IsPostBack)
                this.PopulateView();
        }

        #endregion

        #region Methods

        private void SetScenario() {
            this.languagesManager = new WebTranslatorLanguagesManager();
            this.languagesManager.ReadState();
            this.languages = this.languagesManager.GetSupportedLanguages();
            this.fromLanguage = this.languagesManager.FromLanguage;
            this.toLanguage = this.languagesManager.ToLanguage;

            this.resourcesManager = new TranslatorResourcesManager();
            this.allResources = this.resourcesManager.GetResources();

            string resx = Request["r"];
            if (!String.IsNullOrEmpty(resx))
                this.selectedResource = this.allResources.FirstOrDefault(r => r.Key == resx);
            if (this.selectedResource == null)
                this.selectedResource = this.allResources.First();

            this.resourceKeys = this.selectedResource.GetAllKeys();
        }

        private void PopulateView() {
            this.ddlResources.DataSource = this.allResources;
            this.ddlFromLanguage.DataSource = this.languages;
            this.ddlToLanguage.DataSource = this.languages;
            this.ddlResources.DataBind();
            this.ddlFromLanguage.DataBind();
            this.ddlToLanguage.DataBind();

            this.ddlResources.SelectedValue = this.selectedResource.Key;
            this.ddlFromLanguage.SelectedValue = this.fromLanguage.Name;
            this.ddlToLanguage.SelectedValue = this.toLanguage.Name;

            this.rptResourceItems.DataSource = this.resourceKeys;
            this.rptResourceItems.DataBind();

        }

        protected void lnkChangeParameters_Click(object sender, EventArgs e) {
            Response.Redirect(String.Format("/Translator?r={0}&from={1}&to={2}", Request[this.ddlResources.UniqueID], Request[this.ddlFromLanguage.UniqueID], Request[this.ddlToLanguage.UniqueID]));
        }

        protected void rptResourceItems_ItemDataBound(object sender, RepeaterItemEventArgs e) {
            switch (e.Item.ItemType) {
                case ListItemType.AlternatingItem:
                case ListItemType.Item:
                    string key = (string)e.Item.DataItem;
                    string refText = this.selectedResource.GetText(this.fromLanguage, key);
                    if (String.IsNullOrEmpty(refText)) { // ukrywanie zasobu który nie ma tekstu referencyjnego, ponieważ i tak nie da się go przetłumaczyć
                        e.Item.Visible = false;
                        return;
                    }

                    Label lblComment = e.Item.FindControl("lblComment") as Label;
                    Literal ltlReferenceText = e.Item.FindControl("ltlReferenceText") as Literal;
                    Literal ltlTranslatedText = e.Item.FindControl("ltlTranslatedText") as Literal;
                    ltlReferenceText.Text = HttpUtility.HtmlEncode(refText);
                    ltlTranslatedText.Text = HttpUtility.HtmlEncode(this.selectedResource.GetText(this.toLanguage, key));
                    lblComment.Text = this.selectedResource.GetComment(this.fromLanguage, key);
                    if (String.IsNullOrEmpty(lblComment.Text))
                        lblComment.Visible = false;
                    else
                        lblComment.Text = lblComment.Text.Replace(Environment.NewLine, "<br />");
                    break;
            }
        }

        protected void lnkSave_Click(object sender, EventArgs e) {
            IResourceEditor editor = this.selectedResource.GetEditor(this.toLanguage);
            foreach (string key in this.Request.Form.AllKeys.Where(s => s.EndsWith("-changed"))) {
                if (Request.Form[key] != "1") continue;

                string resourceKey = key.Substring(0, key.Length - 8);
                string text = Request[resourceKey + "-text"];
                editor.SetTranslatedText(resourceKey, text);
            }
            editor.Save();
            editor.Dispose();
            Response.Redirect(Request.RawUrl);
        }

        #endregion

    }
}